package study.spi;

import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;

import java.util.ServiceLoader;

/**
 * JAVA的SPI机制，默认加载META-INF/services下的实现类
 * Dubbo的SPI机制，可以位于下面路径：
 *          META-INF/dubbo/internal
 *          META−INF/dubbo
 *          META-INF/services
 */
public class TestDubboSPI {
    public static void main(String[] args) {

        dubboSPI();
    }

    /**
     * JAVA的SPI机制
     */
    public static void javaSPI(){
        ServiceLoader<HelloService> helloServiceLoader = ServiceLoader.load(HelloService.class);
        System.out.println("-----开始------");
        for(HelloService helloService: helloServiceLoader ){
            helloService.sayHello();
        }
        System.out.println("-----结束------");
    }

    /**
     * Dubbo的SPI机制
     */
    public static void dubboSPI(){

        System.out.println("-----dubboSPI - 开始------");
        // 默认扩展，会加载 @SPI("impl1")
        HelloService helloService = ExtensionLoader.getExtensionLoader(HelloService.class).getDefaultExtension();
        System.out.println("-----dubboSPI -getDefaultExtension------");
        helloService.sayHello();

        HelloService helloService1 = ExtensionLoader.getExtensionLoader(HelloService.class).getExtension("impl1");
        System.out.println("-----dubboSPI -getExtension(\"impl1\")------");
        helloService1.sayHello();

        HelloService helloService2 = ExtensionLoader.getExtensionLoader(HelloService.class).getExtension("impl2");
        System.out.println("-----dubboSPI -getExtension(\"impl2\")------");
        helloService2.sayHello();
        System.out.println("-----dubboSPI -结束------");



        HelloService helloService3= ExtensionLoader.getExtensionLoader(HelloService.class).getAdaptiveExtension();
        System.out.println("-----dubboSPI -getAdaptiveExtension------");
        // 首先创建一个模拟用的URL对象
        URL url = URL.valueOf("dubbo://localhost:20880?t=impl2&hello.service=impl2");
        helloService3.build(url);
        helloService3.build2(url);
        System.out.println("-----dubboSPI -结束------");



    }

}
